package com.hxzy.controller.api.system;

import com.hxzy.common.vo.CodeEnum;
import com.hxzy.common.vo.R;
import com.hxzy.dto.system.DeptSearchDTO;
import com.hxzy.entity.system.SysDept;
import com.hxzy.entity.system.SysPost;
import com.hxzy.service.system.SysDeptService;
import com.hxzy.vo.system.HxzyUser;
import com.hxzy.vo.system.SysDeptTreeVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

@Api(tags = "部门查询")
@RestController
@RequestMapping(value = "/api")
public class SysDeptController {
   @Autowired
    private SysDeptService sysDeptService;
    @ApiOperation(value = "树形")
   @GetMapping(value = "/dept/shuxing")
   public R selectAll( DeptSearchDTO deptSearchDTO){
       List<SysDeptTreeVO> build = this.sysDeptService.buildTreeVo(deptSearchDTO);
       return R.success(build);
   }
    @ApiOperation(value = "查询部门列表")
       @GetMapping(value = "/dept/list")
    public R list(SysDept sysDept){
      return R.success(sysDeptService.selectSysDeptList(sysDept));
    }

    @ApiOperation(value = "新增部门")
    @PostMapping(value = "/dept/add")
    public R add(@RequestBody @Valid SysDept sysDept){
        HxzyUser hxzyUser= (HxzyUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        sysDept.setCreateBy(hxzyUser.getSysUser().getName());
        sysDept.setCreateTime(new Date());
        boolean save = sysDeptService.save(sysDept);
        return save? R.success():R.failed();
    }
    @ApiOperation(value = "修改部门")
    @PostMapping(value = "/dept/update")
    public R updateDept(@RequestBody SysDept sysDept){
        HxzyUser hxzyUser= (HxzyUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        SysDept db = sysDeptService.getById(sysDept.getId());
        if (db!=null){
            BeanUtils.copyProperties(sysDept,db);
            boolean b = this.sysDeptService.updateById(db);
            return b?R.success():R.failed();
        }else {
            return R.failed(CodeEnum.DATE_CATEGORY_FAILED);
        }
    }
}
